package com.riatimes.net.socket
{
	import com.adobe.serialization.json.JSON;
	import com.riatimes.event.SocketEvent;
	import com.riatimes.util.Logger;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.system.System;
	
	import org.puremvc.as3.patterns.observer.Notifier;

	/**
	 * 
	 * @author Nick Wong
	 */
	public class GameSocketService extends Notifier
	{
		private var _gameSocket:GameSocket;//GameSocket对象
		private static var instance:GameSocketService;
	
		private var connected:Boolean=false;//是否建立了socket连接
		/**
		 * 构造函数
		 */
		public function GameSocketService()
		{
			_gameSocket = new GameSocket();
			connected = false;
			System.useCodePage = true;
			_gameSocket.addEventListener(IOErrorEvent.IO_ERROR, IoErro_func);
			_gameSocket.addEventListener(Event.CONNECT, socketConnect);
			_gameSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, SECURITY_EFunc);
			_gameSocket.addEventListener(Event.CLOSE, socketClose);
		}
		
		/**
		 * 发送命令
		 * @param cmd
		 * @param data
		 */
		public function sendCommand(cmd:uint, data:Object):void {
			if(!connected){
				Logger.logError("Socket没有连接上!");
				return;
			}
			var s:String = JSON.encode(data);
			_gameSocket._sendData(cmd, s);
			Logger.logInfo("###########Send  Begin################");
			Logger.logInfo(cmd,s);
			Logger.logInfo("###########Send  END################");
		}
		
		/**
		 * 链接服务器
		 * @param server
		 * @param port
		 */
		public function connect(server:String,port:int):void{
			_gameSocket.connect(server,port);
		}
		
		
		private function socketClose(event:Event) : void
		{
			Logger.logInfo("链接断开");
			connected=false;
			sendNotification(SocketEvent.EVENT_DISCONNECT);
			//connectBtn.visible=true;
			//disconnectBtn.visible=false;
		}
		
		private function IoErro_func(event:IOErrorEvent) : void
		{
			Logger.logError("IO错误");
			sendNotification(SocketEvent.EVENT_IOErrorEvent,event);
		}
		
		private function SECURITY_EFunc(event:SecurityErrorEvent) : void
		{
			Logger.logError("没有权限");
			sendNotification(SocketEvent.EVENT_SECURITY,event);
		}
		
		private function socketConnect(event:Event) : void
		{
			Logger.logInfo("链接成功");
			
			connected = true;
			//_gameSocket._sendData(_uInfo, 0, 100);
			
			sendNotification(SocketEvent.EVENT_CONNECTED);
		}
		
		/**
		 * 返回connected属性，是否已连接上服务器
		 * @return 
		 */
		public function get isConnect():Boolean {
			return connected;
		}
		
		/**
		 * 关闭连接
		 */
		public function close():void{
			if(connected){
				connected=false;
				try{
					_gameSocket.close();
				}catch(e:Error){
					
				}
			}
		}
		
		/**
		 * 获取实例
		 * @return 
		 */
		public static function getInstance():GameSocketService{
			if(instance==null)instance=new GameSocketService();
			return instance;
		}
	}
}